/**
 * 书架
 * 采用MVP设计方式来设计：
 * 1.View：Fragment与Activity实现与用户交互，实现View接口的方法   前端与用户交互
 * 2.Model:数据实体和数据操作，主要是获取数据和数据加载，一般创建一个接口定义数据操作方法，采用一个类来实现。 后台操作：联网获取数据、联网判断
 * 3.Presenter：连接View与Model，一班声明View和Model对象，然后再调用其相应方法完成数据与View的对接！
 */
package com.hzf.booklibrary.ui.fragment;

import android.support.v7.widget.LinearLayoutManager;

import com.hzf.booklibrary.R;
import com.hzf.booklibrary.api.TokenApi;
import com.hzf.booklibrary.api.device.DeviceApi;
import com.hzf.booklibrary.base.BaseRVFragment;
import com.hzf.booklibrary.base.Constant;
import com.hzf.booklibrary.bean.book.Book;
import com.hzf.booklibrary.bean.clazz.Clazz;
import com.hzf.booklibrary.bean.device.Deviceinfo;
import com.hzf.booklibrary.bean.token.TokenBean;
import com.hzf.booklibrary.component.AppComponent;
import com.hzf.booklibrary.component.DaggerMainComponent;
import com.hzf.booklibrary.ui.activity.BookDetailActivity;
import com.hzf.booklibrary.ui.contract.RecommendContract;
import com.hzf.booklibrary.ui.easyadapter.BookListAdapter;
import com.hzf.booklibrary.ui.easyadapter.RecommendAdapter;
import com.hzf.booklibrary.ui.presenter.RecommendPresenter;
import com.hzf.booklibrary.utils.LogUtils;
import com.hzf.booklibrary.utils.NetworkUtils;
import com.hzf.booklibrary.view.recyclerview.adapter.RecyclerArrayAdapter;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class RecommendFragment extends BaseRVFragment<RecommendPresenter, Book>
        implements RecommendContract.View, RecyclerArrayAdapter.OnItemLongClickListener {

    private int pageCount = 1;
    private String queryKey = "推荐";
    private int id = -1;
    private int classNumber;
    private String deviceOrgid;
    private String token;

    @Override
    public int getLayoutResId() {
        return R.layout.fragment_recommend;
    }

    @Override
    public void initDatas() {
        //   EventBus.getDefault().register(this);
        //发出请求获取图书列表
        TokenApi.getInstance().getToken(Constant.CLIENT_ID_VALUE, Constant.CLIENT_SECRET_VALUE)
                .enqueue(new Callback<TokenBean>() {
                    @Override
                    public void onResponse(Call<TokenBean> call, Response<TokenBean> response) {
                        String token = response.body().getData().getToken();
                        getDeviceInfo(token);
                        com.blankj.utilcode.util.LogUtils.i("token==" + token);
                    }

                    @Override
                    public void onFailure(Call<TokenBean> call, Throwable t) {

                    }
                });
//        classNumber = SharedPreferencesUtil.getInstance().getInt("classNumber");
//        deviceOrgid = SharedPreferencesUtil.getInstance().getString("deviceOrgid");
//        token = SharedPreferencesUtil.getInstance().getString("token");
//        com.blankj.utilcode.util.LogUtils.i("classNumber=" + classNumber + "deviceOrgid==" + deviceOrgid + "token==" + token);

    }

    public void getToken(){
        TokenApi.getInstance().getToken(Constant.CLIENT_ID_VALUE, Constant.CLIENT_SECRET_VALUE)
                .enqueue(new Callback<TokenBean>() {
                    @Override
                    public void onResponse(Call<TokenBean> call, Response<TokenBean> response) {
                        String token = response.body().getData().getToken();
                        getDeviceInfo(token);
                        com.blankj.utilcode.util.LogUtils.i("token==" + token);
                    }

                    @Override
                    public void onFailure(Call<TokenBean> call, Throwable t) {

                    }
                });
    }


    public void getDeviceInfo(final String token) {
        DeviceApi.getInstance().getDeviceInfo(token, NetworkUtils.getWifiMac())
                .enqueue(new Callback<Deviceinfo>() {
                    @Override
                    public void onResponse(Call<Deviceinfo> call, Response<Deviceinfo> response) {
                        String deviceOrgid = response.body().getData().getDeviceOrgid();
                        String deviceId = response.body().getData().getDeviceId();
                        getClazzInfo(token, deviceId, deviceOrgid);
                    }

                    @Override
                    public void onFailure(Call<Deviceinfo> call, Throwable t) {

                    }
                });
    }


    public void getClazzInfo(final String token, String deviceId, final String deviceOrgid) {
        TokenApi.getInstance().getClazzInfo(token, deviceId)
                .enqueue(new Callback<Clazz>() {
                    @Override
                    public void onResponse(Call<Clazz> call, Response<Clazz> response) {
                        int classNumber = response.body().getData().getClassNumber();
                        mPresenter.getBooksList(token, classNumber, deviceOrgid, 1, 100);
                    }

                    @Override
                    public void onFailure(Call<Clazz> call, Throwable t) {

                    }
                });
    }

    @Override
    public void configViews() {
        if ("推荐".equals(queryKey)) {
            initAdapter(RecommendAdapter.class, true, false);
            RecommendAdapter.setRecyclerView(mRecyclerView);
        } else {
            initAdapter(BookListAdapter.class, true, true);
            if (mRecyclerView != null) {
                mRecyclerView.setLayoutManager(new LinearLayoutManager(getSupportActivity()));
                mRecyclerView.removeAllItemDecoration();
                mRecyclerView.setItemDecoration(R.drawable.book_shelf_touch_bg,
                        getResources().getDimensionPixelOffset(R.dimen.dimen_1dp), 0, 0, getSupportActivity());
                BookListAdapter.setRecyclerView(mRecyclerView);
            }
        }

        mAdapter.setOnItemLongClickListener(this);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerMainComponent.builder()
                .appComponent(appComponent)
                .build()
                .inject(this);
    }
//    @Override
//    public void showBooksList(List<Recommend.RecommendBooks> list) {

//        LogUtils.e("mRecyclerView count after:"+count);
//        LogUtils.e("mAdapter count after:"+count1);
//    }

    @Override
    public void onItemClick(int position) {
        BookDetailActivity.startActivity(getSupportActivity(), mAdapter.getItem(position));
    }


    @Override
    public boolean onItemLongClick(int position) {
        return false;
    }

    //加载更多
    @Override
    public void onLoadMore() {
        super.onLoadMore();
        LogUtils.i("加载更多");
//        pageCount++;
//        getToken();
//        mPresenter.getBooksList(token, classNumber, deviceOrgid, pageCount, 10);

//        pageCount++;
//        LogUtils.e(pageCount);
//        mPresenter.getBooksList(""+pageCount,queryKey,id);


    }

    //刷新
    @Override
    public void onRefresh() {
        super.onRefresh();
        mRecyclerView.setRefreshing(false);
//        mAdapter.clear();
//        getToken();
//        mPresenter.getBooksList(token, classNumber, deviceOrgid, 1, 10);
//        pageCount = 1;
    }

    @Override
    public void showError() {
        loaddingError();
    }

    @Override
    public void complete() {
        mRecyclerView.setRefreshing(false);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
//        //取消注册EventBus
//        EventBus.getDefault().unregister(this);
    }

    @Override
    public void showBooksList(List<Book> list) {
        int count = mRecyclerView.getRecyclerView().getChildCount();
        int count1 = mAdapter.getCount();

        mAdapter.addAll(list);
        mAdapter.getCount();
        count1 = mAdapter.getCount();
        count = mRecyclerView.getRecyclerView().getChildCount();
        complete();
    }
}
